package com.baiyun.lease.web.app.service.impl;

import com.baiyun.lease.common.constant.RedisConstant;
import com.baiyun.lease.common.exception.LeaseException;
import com.baiyun.lease.common.login.LoginUser;
import com.baiyun.lease.common.login.LoginUserHolder;
import com.baiyun.lease.common.result.ResultCodeEnum;
import com.baiyun.lease.common.utils.JwtUtil;
import com.baiyun.lease.common.utils.VerifyCodeUtil;
import com.baiyun.lease.model.entity.UserInfo;
import com.baiyun.lease.model.enums.BaseStatus;
import com.baiyun.lease.web.app.service.LoginService;
import com.baiyun.lease.web.app.service.SmsService;
import com.baiyun.lease.web.app.service.UserInfoService;
import com.baiyun.lease.web.app.vo.user.LoginVo;
import com.baiyun.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getSMSCode(String phone) {
        //1. 检查手机号码是否为空
        if (phone == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //2.判断redis中的key是否失效
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean bo = stringRedisTemplate.hasKey(key);
        if (bo) {
            //3.查看验证码在redis中的有效时间，设置一分钟之内不允许再次获取验证码
            Long expire = stringRedisTemplate.getExpire(key);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //4.发送验证码,随机生成一个六位数字的验证码
        String code = VerifyCodeUtil.getVerifyCode(6);
        smsService.sendCode(phone,code);
        //5.将验证码存放在redis上,设置过期时间600秒
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断手机号码和验证码是否为空
        if (!StringUtils.hasText(loginVo.getPhone())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //2.获取redis中的验证码信息
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = stringRedisTemplate.opsForValue().get(key);
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //3.通过手机号码查询用户是否存在，如果不存的对用户进行注册登录
        UserInfo userInfo = userInfoService.lambdaQuery()
                .eq(UserInfo::getPhone, loginVo.getPhone())
                .one();
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+loginVo.getPhone().substring(6));
            userInfoService.save(userInfo);
        }
        //4.判断用户是否被禁用
        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //5.创建token返回
        return JwtUtil.createToken(userInfo.getId(), loginVo.getPhone());
    }

    @Override
    public UserInfoVo getLoginUserInfo(Long id) {
        UserInfo userInfo = userInfoService.getById(id);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }

}
